package com.cm.sys.system.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import org.springframework.stereotype.Repository;

@Repository
public interface BaseDao {

    @SelectProvider(type = SqlProvider.class, method = "getSql")
    Object getObject(@Param("sql") String sql, @Param("args") Object[] args);

    @SelectProvider(type = SqlProvider.class, method = "getSql")
    Map<String, Object> getMap(@Param("sql") String sql, @Param("args") Object[] args);

    @SelectProvider(type = SqlProvider.class, method = "getSql")
    List<Map<String, Object>> getListMap(@Param("sql") String sql, @Param("args") Object[] args);

    @DeleteProvider(type = SqlProvider.class, method = "getSql")
    int delete(@Param("sql") String sql, @Param("args") Object[] args);

    @UpdateProvider(type = SqlProvider.class, method = "getSql")
    int update(@Param("sql") String sql, @Param("args") Object[] args);

    class SqlProvider {
        public String getSql(Map map) {
            String sql = map.get("sql").toString();
            char[] chars = sql.toCharArray();
            StringBuffer bf = new StringBuffer();
            int index = 0;
            for (char c : chars) {
                if ('?' == c) {
                    bf.append("#{args[" + index + "]}");
                    index++;
                } else {
                    bf.append(c);
                }
            }
            return bf.toString();
        }
    }
}
